<template>
    <div class="dooya-container">
        <Card>
            <!-- 操作 -->
            <div style="margin: 10px 0;display:flex;justify-content:end;">
                <Button type="primary" icon="md-add" to="/inneruser/innergroupedit">新增角色</Button>
                
                <Button v-if="anim1" @click="anim1 = !anim1" style="margin-left: 10px;height:30px;" type="success" icon="ios-arrow-dropup">隐藏</Button>
                <Button v-else  @click="anim1 = !anim1" style="margin-left: 10px;height:30px;" type="success" icon="ios-arrow-dropdown">展开</Button>
            </div>
                        <hr>
            <transition name="fade">
                <div v-show="anim1" >
                    <template>
                        <Form    ref="formItemSearch" :model="searchData"  :rules="searchDataRule" :label-width="120" inline  style="margin-top: 20px;" class="form-user">

                            <FormItem class="custom-label" label="请输入关键字：" style="min-width: 320px;font-size: 14px;" prop="keywords">
                                <Input v-model="searchData.keywords" placeholder="请输入用户组名"></Input>
                            </FormItem>
                      
                            <br/>
                            <Row>
                                <Col span="22" offset="0"  style="height: 50px; display:flex;justify-content:center;align-items:center;">
                                    <FormItem>
                                        <Button type="primary" icon="ios-search"  @click="handleSubmit('formItemSearch')">查询</Button>
                                        <Button icon="ios-trash-outline"   @click="handleReset('formItemSearch')" style="margin-left: 8px">清除</Button>
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </template>
                </div>
             </transition>

            <!-- 表格 -->
            <Table stripe border :data="tableData"  :columns="tableColumns"  style="margin-top: 20px;"></Table>
            <div style="margin: 10px;overflow: hidden">
                <div style="float: right;">
                    <Page show-sizer transfer placement="top" :total="tableDataOrg.length" :current.sync="pageNum"
                        :page-size-opts="[10, 50, 100, 200]" :page-size="pageSize" @on-change="changePage"
                        @on-page-size-change="changePageSize"></Page>
                </div>
            </div>

              
            <!-- Modal - 组用户 -->
            <Modal title="编辑组用户" v-model="modalShowRole"   :mask-closable="false" :closable="true"    @on-ok="handleSubmitModal"  >
                 <p slot="header" style="color: #34383c;;text-align:left">
                    <Icon type="ios-information-circle"></Icon>
                    <span>编辑用户组- <font color="red">{{ current_role_name }}</font></span>
                </p>
                    <Transfer
                        :data="usersLeft"
                        :target-keys="usersRight"
                        :list-style="listStyle"
                        :titles='["所有用户", "已选中用户"]'
                        filterable
                        :filter-method="filterMethod"

                        virtual
                        
                        :render-format="render1"
                        
                        @on-change="handleChange">
                    </Transfer>
            </Modal>
        </Card>




    </div>
</template>

<script>
import { toolTip } from "@/libs/util";
// vuex
import store from "@/store";
// mockData
import {
    userList, // 用户列表
    roleList // 角色列表
    // menuList // 菜单列表
} from "@/mock/role";
// function
import {
    computedMenuData, // 菜单数据转换成iview树形数据结构(多层)
    resultCallback, // 根据请求的status执行回调函数
    getValueByKey // 根据对象数组某个key的value，查询另一个key的value
} from "@/libs/dataHanding";
// api
import {
    saveGroupUsers, // 保存角色对应的用户数据
    getGroupUsers, // 获取组用户根据role_id
    getAllUsers, //获取所有用户
    delGroup, //删除组
    getGroupList // 获取角色列表
} from "@/api/data";
import { refreshRoute } from "@/router"; // 路由初始化，清空动态路由

export default {
    data() {
        return {
            anim1: true,
            searchData: {
                keywords: ""
            },
            /* 每页 */
            tableDataOrg: [], // 原始数据
            tableData: [], // 处理后的当页数据
            tableColumns: [
                {
                    title: "序号",
                    key: "id",
                    align: "center",
                    minWidth: 50
                },
                {
                    title: "用户组",
                    key: "role_name",
                    align: "center",
                    minWidth: 100
                },
                {
                    title: "用户组成员",
                    key: "user_names",
                    align: "center",
                    minWidth: 100,
                    ellipsis: true, //超出长度时用...显示
                    render: (h, params) => {
                        return toolTip(h, 1, params.row.user_names);
                    }
                },
                {
                    title: "操作",
                    key: "action",
                    minWidth: 150,
                    align: "center",
                    render: (h, params) => {
                        return h("div", [
                            h(
                                "Button",
                                {
                                    props: {
                                        type: "text",
                                        size: "small"
                                    },
                                    style: {
                                        color: "#1E90FF",
                                        marginRight: "5px"
                                    },
                                    on: {
                                        click: () => {
                                            this.edit(params.row);
                                        }
                                    }
                                },
                                "修改名称及权限"
                            ),
                            h(
                                "Button",
                                {
                                    props: {
                                        type: "text",
                                        size: "small"
                                    },
                                    style: {
                                        color: "#1E90FF",
                                        marginRight: "5px"
                                    },
                                    on: {
                                        click: () => {
                                            //组用户弹框处理
                                            this.editGroup(
                                                params.row.id,
                                                params.row
                                            );
                                        }
                                    }
                                },
                                "成员管理"
                            ),
                            h(
                                "Tooltip",
                                {
                                    props: {
                                        trigger: "hover",
                                        content: "删除",
                                        placement: "top",
                                        transfer: true
                                    }
                                },
                                [
                                    h("Button", {
                                        props: {
                                            type: "error",
                                            size: "small",
                                            icon: "md-close",
                                            disabled:
                                                params.row.name ===
                                                "super_admin"
                                        },
                                        on: {
                                            click: () => {
                                                this.del(params.row);
                                            }
                                        }
                                    })
                                ]
                            )
                        ]);
                    }
                }
            ], // 表头列项
            pageNum: 1, // 页码
            pageSize: 10, // 每页显示数量
            /* loading */
            tableLoading: false, // table
            buttonLoading: false, // button

            /* modal弹框 */
            current_role_name: "",
            modalShowRole: false, // 是否显示 - role
            allUsers: [],
            usersLeft: [],
            usersRight: [],
            roleUserIds: [], //弹框出现的时候单个角色对应的所有用于ids
            modalRoleId: 0,
            listStyle: {
                width: "200px",
                height: "300px"
            },

            searchDataRule: {
                keywords: [
                    {
                        type: "string",
                        max: 20,
                        message: "组名称过长",
                        trigger: "change"
                    }
                ]
            }
        };
    },
    async created() {
        this.getData();
        //this.getAllGroupUsers();
    },
    methods: {
        render1(item) {
            return item.label;
        },
        handleChange(newTargetKeys) {
            this.usersRight = newTargetKeys;
        },
        filterMethod(data, query) {
            return data.label.indexOf(query) > -1;
        },

        //成员管理确认后 保存数据
        async handleSubmitModal() {
            //请求后端数据
            let group_data = {};
            group_data.role_id = this.modalRoleId;
            group_data.user_id_source = this.roleUserIds.join(","); // 这个角色保存前对应的用户ids  string
            group_data.user_id_result = this.usersRight.join(","); // 这个角色保存后对应的用户ids  string

            let res_group = await saveGroupUsers(group_data);

            if (res_group.data.code != 0) {
                //axios.js 已经截取了错误信息，这里不需要提示了。
            } else {
                resultCallback(200, "添加成功！", () => {
                    this.getData();
                    this.modalShowRole = false;
                });
            }
        },

        // 成员管理 弹框：
        async editGroup(role_id, row) {
            console.log("edit-group:", role_id);
            this.modalShowRole = true;
            this.modalRoleId = role_id;
            this.current_role_name = row.role_name;
            // 获取单个角色的所有用户id
            this.roleUserIds =
                (await getGroupUsers({ role_id: role_id })).data.data || [];

            console.log("roleUserIds:", this.roleUserIds);

            let a = [];
            let b = [];
            let allUsers = this.allUsers;
            console.log("=allUsers:===", allUsers);

            for (let i = 0; i < allUsers.length; i++) {
                a.push({
                    key: allUsers[i].id.toString(),
                    label: allUsers[i].real_name
                });

                if (
                    this.roleUserIds &&
                    this.roleUserIds.some(ele => ele === allUsers[i].id)
                ) {
                    b.push(allUsers[i].id.toString());
                }
            }
            this.usersLeft = a;
            this.usersRight = b;

            console.log("usersLeft-----:", a);
            console.log("usersRight-----:", b);
        },

        //修改名称及权限
        edit(row) {
            console.log("edit-row:", row);
            this.$router.push({
                name: "innergroupedit",
                params: row
            });
        },

        // 点击表单按钮 - 查询
        handleSubmit() {
            this.$refs.formItemSearch.validate(async valid => {
                if (valid) {
                    this.getData();
                }
            });
        },

        // 获取首页数据
        async getData() {
            this.tableLoading = true;

            let paramData = {
                keywords: this.searchData.keywords,
                page: this.pageNum,
                length: this.pageSize
            };
            console.log("paramData:", paramData);

            this.tableDataOrg = (await getGroupList(paramData)).data.data;

            //
            this.allUsers = (await getAllUsers()).data.data || [];

            //

            this.refreshData();
            this.buttonLoading = false;
            this.tableLoading = false;
        },
        // 根据条件刷新数据
        refreshData() {
            this.tableDataOrg.forEach(role => {
                // 给每个role的menus设置title
                // role.menus.forEach(menu => {
                //   this.$set(
                //     menu,
                //     "title",
                //     getValueByKey(this.menuListNotComputed, "id", menu.id, "title")
                //   );
                // });
            });
            // 分页 & 每页条数
            this.tableData = this.tableDataOrg.slice(
                (this.pageNum - 1) * this.pageSize,
                this.pageNum * this.pageSize
            );
            // 如果是在删除之后获取的数据 -> 若删掉的是某一页的最后项且页码不是1，则自动获取前一页的数据
            if (this.tableData.length === 0 && this.tableDataOrg.length !== 0) {
                this.pageNum--;
                this.getData();
            }
        },
        // 分页
        changePage(pageNum) {
            this.pageNum = pageNum;
            this.refreshData();
        },
        // 每页条数变化
        changePageSize(pageSize) {
            this.pageSize = pageSize;
            this.pageNum = 1;
            this.refreshData();
        },

        // 点击按钮 - 删除
        del(row) {
            this.$Modal.confirm({
                title: "删除用户组不能恢复，确定删除？",
                onOk: async () => {
                    //请求后端数据
                    let data = {};
                    data.role_id = row.id;
                    let res = await delGroup(data);

                    if (res.data.code != 0) {
                        //axios.js 已经截取了错误信息，这里不需要提示了。
                    } else {
                        resultCallback(200, "修改成功！", () => {
                            this.getData();
                            //弹框角色id 变0；
                            this.modalRoleId = 0;
                            this.roleUserIds = [];
                        });
                    }
                },
                closable: true
            });
        },
        handleReset(name) {
            this.$refs[name].resetFields();
        }
    }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.dooya-container /deep/ {
    .ivu-table-body {
        overflow: hidden;
    }

    .ivu-table {
        th {
            text-align: center;
        }

        td {
            padding: 10px 0;
        }
    }
}

.v-transfer-dom /deep/ {
    .ivu-modal {
        .ivu-form {
            .menu-function,
            .users {
                margin-bottom: 14px;
            }

            .ivu-tree {
                &-children {
                    li {
                        margin: 0;
                    }
                }
            }
        }
    }
}
</style>
